/**
 * 
 */
package name.webdizz.gadget.four.envelope.client.util;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.i18n.client.constants.DateTimeConstants;

/**
 * @author Izzet_Mustafayev
 * 
 */
public class Dates {
	/**
	 * Holds human readable date format.
	 */
	private static final String HUMAN_FORMAT = "E, dd MMM";

	/**
	 * Holds today {@link Date}.
	 */
	private static final Date TODAY_DATE = new Date();

	/**
	 * Holds date format accepted by remote services.
	 */
	public static final String FORMAT = "yyyy-MM-dd";

	/**
	 * Holds today date accepted by remote services.
	 */
	public static final String TODAY = DateTimeFormat.getFormat(FORMAT).format(
			TODAY_DATE);

	/**
	 * Holds milliseconds within one day.
	 */
	private static final int DAY_LENGTH = 1000 * 60 * 60 * 24;

	/**
	 * Holds reference to {@link DateTimeConstants} instance.
	 */
	private static final DateTimeConstants DATE_TIME_CONSTANTS = LocaleInfo
			.getCurrentLocale().getDateTimeConstants();

	/**
	 * Holds today week day short name.
	 */
	private static final String TODAY_WEEK_DAY = DateTimeFormat.getFormat("E")
			.format(TODAY_DATE);

	private Dates() {
		super();
	}

	/**
	 * Resolves week begin date and return according {@link Dates.FORMAT}
	 * 
	 * @return week begin date
	 */
	public static String getWeekBeginDate() {
		String result = TODAY;
		int todayWeekDayNum = getWeekDay();
		// resolve date according to day of a week
		if (todayWeekDayNum > 0) {
			result = DateTimeFormat.getFormat(FORMAT).format(
					new Date(TODAY_DATE.getTime() - (todayWeekDayNum - 1)
							* DAY_LENGTH));
		}
		return result;
	}

	private static int getWeekDay() {
		int result = 0;
		String[] weekDays = DATE_TIME_CONSTANTS.shortWeekdays();
		for (int i = 0; i < weekDays.length; i++) {
			if (TODAY_WEEK_DAY.equals(weekDays[i])) {
				result = i;
				break;
			}
		}

		return result;
	}

	/**
	 * Resolves more human readable date representation from given string
	 * formatted as YYYY-mm-dd.
	 * 
	 * @param date
	 *            the date representation to resolve from
	 * @return resolved more human readable date representation
	 */
	public static String getReadableDate(final String date) {
		return DateTimeFormat.getFormat(Dates.HUMAN_FORMAT).format(
				DateTimeFormat.getFormat(FORMAT).parse(date));
	}
}
